//index.js
//获取应用实例
import CommonPage from "../common/CommonPage.js"
const app = getApp()
const util = require('../../utils/util')
const api = require('../api/http.js')
const config = require('../../config')

class IndexPage extends CommonPage {
  constructor(...args) {
    super(...args)
    super.$init({
      loadFlag: true,
      merchList: [],
      userInfo: null,
      hasUserInfo: false,
      // canIUse: wx.canIUse('button.open-type.getUserInfo'),
      stepInfoList: null,
      stepInfo: {},
      hasStepInfo: false,
      step: 0,
      ldt: 0,
      lifeVal: 0, //活力值
      calcVal: 0,
      daoCoin: 0,
      userId: null,
      token: null,
      height: '128rpx',
      isRegister: false,
      modalPattern: {},
      modalCancelEvent: "hideModal",
      modalConfirmEvent: "hideModal",
      modalArgs: null,
      nannerTitleColorLeft: "#4D7BFE",
      nannerTitleColorRight: "#000",
      bannerIndex: 0,
      showImage: false,
      titleName: '叨币道',
      backImagePath: getApp().globalData.backImagePath
    })
  }

  onLoad = function(query) {
    this.modal = this.selectComponent("#myModal")
    var that = this
    var mList = wx.getStorageSync('merchList')
    if (mList) {
      this.setData({
        merchList: mList
      })
    } else if (app.globalData.merchList) {
      this.setData({
        merchList: app.globalData.merchList
      })
    }
    var user = wx.getStorageSync('userInfo')
    //app.globalData 可能还没同步要用本地缓存
    console.log("本地缓存 userInfo:", user)
    if (user.openId) {
      this.setData({
        userInfo: user,
        hasUserInfo: true
      })
    } else {
      wx.getSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function (res) {
                //用户已经授权过
                // console.log("GetUserInfo-res:", res)
                /*
                //后台解密会出错，故只从后台获取openId信息
                // var encry = res.encryptedData
                // var iv = res.iv
                */
                app.globalData.userInfo = res.userInfo
                that.getOpenId()
              }
            });
          } else {
            wx.showToast({
              title: '未正常授权，请删除后重新登录！',
              icon: 'None',
              duration: 1500,
            })
            return
          }
        }
      })
    }
    
    //微信运动授权
    wx.authorize({
      scope: 'scope.werun',
      success: () => {
        console.log("用户授权微信运动！")
        this.getStepInfo(user, true) //首次加载获取 
      }
    })
}

// onShow() {  //这种方式会导致函数有时无法被调用
onShow = function() {
  var that = this
  if (!this.data.hasUserInfo) {
    wx.showToast({
      title: '请先授权登录！',
      icon: 'none',
      image: '',
      duration: 1000,
      mask: true,
      success: function (res) {
      },
      fail: function (res) { },
      complete: function (res) {
        that.refreshMerchandiseList()
      },
    })

  } else {
    if (!this.data.loadFlag) {
      that.getStepInfo(this.data.userInfo)  //更新步数信息
      this.showCall()
    } else {
      this.setData({
        loadFlag: false
      })
    }
  }
}
onReady = function() {
  // this.modal = this.selectComponent("#myModal")
}
//下拉刷新
onPullDownRefresh = function () {
  var that = this
  if (!this.data.hasUserInfo) {
    //用户一开始没有授权直接回到小程序主页
    console.log("用户一开始没有授权直接回到小程序主页")
    wx.showToast({
      title: '未正常授权！请退出重新登录',
      icon: 'none',
      duration: 1500,
      mask: true,
    })
  } else {
    that.getStepInfo(that.data.userInfo)
    that.showCall(false)
  }
  wx.stopPullDownRefresh()  //解决下拉刷新不回弹bug
}

showModal = function() {
  this.modal.showModal()
}

hideModal = function() {
  this.modal.hideModal()
}

//用户点击分享
onShareAppMessage = function(res) {
  console.log("分享信息：", res)
  if (res.from === 'button') {
    var id = res.target.id
    if (!this.data.hasUserInfo) {
      wx.showToast({
        title: '错误!请先授权登录！',
        icon: 'none',
        image: '',
        duration: 2000,
        mask: true,
        success: function (res) {
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {

      var user = this.data.userInfo
      var step = this.data.step

      if (id === 'share') {
        return {
          title: "找回童年的回忆^_^!!!",
          desc: user.nickName + "邀您一起玩叨币道赢奖品！TAT",
          imageUrl: "http://cmechat.xyz/daobidao/uploads/images/logo.png",
          path: "/pages/index/auth/auth",
        }
      } else if (id === 'shareInv') {
        return {
          title: user.nickName + "发起了叨币换礼物，快来帮帮TAT！",
          desc: "使用叨币就可换取童年回忆！",
          imageUrl: "http://cmechat.xyz/daobidao/uploads/images/logo.png",
          path: "/pages/index/auth/auth?pageId=1&name=" + user.nickName + "&step=" + step + "&openId=" + user.openId,
          success: function (re) {
            console.log("分享返回值：", re)
            wx.getShareInfo({
              success: function (re) {
                console.log("share info:", re)
              }
            })
          },
        }
      }
    }
  }
}
//onShow回调
showCall = function (showFlag) {
  console.debug("showCall!")
  this.refreshMerchandiseList()
  this.getLDT(showFlag)
}
//获取商品列表
refreshMerchandiseList = function () {
  var that = this
  api.get(config.merchandiseListUrl).then(res => {
    console.debug("商品列表：\n", res)
    if (res.length != 0) {
      app.globalData.merchList = res
      that.setData({
        merchList: res
      })
      console.debug("Refresh merchandise list done!")
      console.debug(app.globalData.suitList)
    }
  }).catch(e => {
    console.error(e.errMsg)
  })
}
//获取LDT总数
getLDT = function (showFlag) {
  var that = this
  var v = this.data
  console.debug("Data", v)
  if (showFlag == false) return
  if (this.data.loadFlag) {
    this.setData({
      loadFlag: false
    })
    return
  }
  if (v.userId == null) {
    that.setData({
      modalPattern: {
        title: "提示",
        content: "登录叨币道App领取叨币啊^_^",
        confirmText: "登录",
        cancelText: "等等",
      },
      modalConfirmEvent: "loginDaobidao",
      modalArgs: null
    },
      this.showModal()
    )
  } else {
    var param = {
      userId: v.userId,
      token: v.token
    }
    api.post(config.getLDTUrl, param).then(res => {
      console.debug("Get MyLada return:\n", res)
      var r = res.result
      if (r !== undefined) {
        var ldt = Math.floor(r.totalAmount)
        app.globalData.ldt = ldt
        that.setData({
          ldt: ldt,
          calcVal: Math.floor(ldt / 12)
        })
        console.debug("Total amount:\n", r.totalAmount)
      } else {
        console.log("Res massage:\n", res.msg)
      }
    }).catch(e => {
      console.log(e)
    })
  }
}

toInvitation = function(arg) {
  console.log("分享参数：\n", arg)
  wx.removeStorageSync("invitation")
  this.$route({path: './invitation/invitation', query: arg, clazzName: 'InvitationPage'})
}
getOpenId = function (cb, arg) {
  var loginCode = null
  wx.login({
    success: res => {
      if (res.code) {
        var param = {
          code: res.code
        }
        api.post(config.userInfoUrl, param).then(re => {
          console.debug("getOpneId:\n", re)
          var user = re.userInfo
          if (user) {
            console.log("openId", user.openId)
            app.globalData.openId = user.openId
            app.globalData.unionId = user.unionId
            app.globalData.userInfo['openId'] = user.openId
            app.globalData.userInfo['unionId'] = user.unionId
            wx.setStorageSync('userInfo', app.globalData.userInfo)
            app.globalData.hasUserInfo = true
            that.setData({
              userInfo: app.globalData.userInfo,
              hasUserInfo: true
            })
            util.registerUser(app.globalData.userInfo)
          }
        })
      } else {
        console.error("Login for code failed!")
        wx.showToast({
          title: '登录信息获取失败！',
          icon: 'none'
        })
      }
    }
  })
}
//获取步数差
getBalanceStep = function (openId, step) {
  var that = this
  var param = {
    openId: openId
  }
  api.post(config.balanceStepUrl, param).then(res => {
    var bStep = res
    var tStep = step + bStep
    if (tStep < 0) {
      tStep = 0
    }
    var lval = Math.floor(tStep / 1000)
    app.globalData.step = tStep
    that.setData({
      step: tStep,
      lifeVal: lval
    },
      console.log("获取步数成功！", tStep)
    )
  })
}
stepInfoCall = function (userInfo, stepInfo, inv = false) {
  console.debug("获取步数回调：", userInfo, stepInfo)
  if (inv) {
    var invInfo = wx.getStorageSync('invitation')
    if (invInfo.openId) {
      var query = {
        myOpenId: userInfo.openId,
        myStep: stepInfo.step,
        myName: userInfo.nickName,
        friendOpenId: invInfo.openId,
        friendName: invInfo.name,
        friendStep: invInfo.step
      }
      this.toInvitation(query)
    }
  }
  this.getBalanceStep(userInfo.openId, stepInfo.step)
}
getStepInfo = function(arg, inv = false) {
  console.debug("开始获取步数！")
  var that = this
  wx.login({
    success: resLogin => {
      if (resLogin.code) {
        wx.getSetting({
          success(res) {
            if (res.authSetting['scope.werun']) {
              wx.getWeRunData({
                success(resRun) {
                  console.debug("已获取步数解密数据！")
                  const encryptedData = resRun
                  //3、解密步骤2的数据；
                  var param = {
                    encryptedData: resRun.encryptedData,
                    iv: resRun.iv,
                    code: resLogin.code
                  }
                  api.post(config.stepInfoUrl, param).then(res => {
                    console.debug("请求步数数据")
                    var runData = res.stepInfo
                    if (runData.stepInfoList) {
                      runData.stepInfoList = runData.stepInfoList.reverse()
                      //生成日期              
                      for (var i in runData.stepInfoList) {
                        runData.stepInfoList[i].date = util.formatTime(new Date(runData.stepInfoList[i].timestamp * 1000))
                      }
                      app.globalData.stepInfoList = runData.stepInfoList
                      app.globalData.stepInfo = runData.stepInfoList[0]
                      app.globalData.hasStepInfo = true
                      var step = runData.stepInfoList[0].step
                      that.setData({
                        hasStepInfo: true,
                        stepInfoList: runData.stepInfoList,
                        stepInfo: runData.stepInfoList[0],
                      },
                        that.stepInfoCall(arg, runData.stepInfoList[0], inv)
                      )
                    }
                  }).catch(e => {
                    console.log(e)
                  })
                },
                fail(res) {
                  console.error("getWeRun failed", res.errMsg)
                }
              })
            } else {
              wx.showToast({
                title: '请先到"我的-授权管理"开启微信运动^_^',
                icon: 'none'
              })
            }
          }
        })
      } else {
        console.log('获取用户登录态失败！' + resLogin.errMsg)
      }
    }
  })
}



//登录叨币道领取奖励
signinDaobidao = function() {
  var that = this
  var v = this.data
  if (!v.hasUserInfo) {
    wx.showToast({
      title: "请您先授权登录^_^",
      icon: 'none',
      duration: 1000,
    })
  } else {
    if (!that.data.isRegister) {
      that.loginDaobidao(false)
    } else {
      if (this.data.userId != null) {
        this.getRewards(this.data.userId, this.data.token)
      }
    }
  }
}
//获取当日LDT奖励
getRewards = function(userId, token) {
  var that = this
  var param = {
    userId: userId,
    token: token,
  }
  api.post(config.getRewardsUrl, param).then(res => {
    console.debug("GetRewards return:", res)
    var r = res.result
    if (r !== undefined) {
      var ldt = r.scoreOfThisTime
      var str = '恭喜获得 ' + ldt + ' LDT. ^_^'
      if (!r.firstOfToday) {
        str = '今日已经领过啦,去叨币道赚取更多的叨币吧'
      }
      that.getLDT()
      wx.showToast({
        title: str,
        icon: 'none',
        duration: 2000,
      })
    } else {
      console.log("失败！")
    }
  })
}

//注册登录叨币道app
loginDaobidao = function(showFlag) {
  if (showFlag) {
    this.hideModal()
  }
  var that = this
  var user = this.data.userInfo
  console.debug("User Info:\n", user)
  var param = {
    openId: user.openId
  }
  api.post(config.loginDaobidaoUrl, param).then(res => {
    console.debug("Login Return:", res)
    var v = res.result
    if (v !== undefined) {
      that.setData({
        isRegister: true,
        userId: v.id,
        token: v.token,
        ldt: Math.floor(v.score),
        calcVal: Math.floor(v.score / 12)
      })
      that.getRewards(v.id, v.token)
    } else {
      console.error(res.msg)
    }
  }).catch(e => {
    console.error(e);
  })
}

//商品详情页
toMerchDetail = function(dat) {
  console.debug("TO Detail:\n", dat)
  var arg = dat.currentTarget.dataset
  this.$route({path: "./merchDetail/merchDetail", query: arg, clazzName: "MerchDetailPage"})
}
//确认兑换
exchangeConfirm = function(e) {
  this.hideModal()
  console.debug("确认兑换:\n", e)
  var that = this
  var user = app.globalData.userInfo
  var data = e.currentTarget.dataset.args
  var daoCoin = data.coin
  that.setData({
    daoCoin: daoCoin
  })
  if (daoCoin < data.price) {
    that.toMerchDetail(data)
  } else {
    var param = {
      openId: user.openId,
      tokenId: that.data.token,
      userId: that.data.userId,
      merchId: data.id,
      step: that.data.step,
      ldt: Math.floor(that.data.ldt)
    }
    console.log(param)
    api.post(config.exchangeMerchandiseUrl, param).then(res => {
      console.log("兑换返回结果", res)
      if (res == "OK" || res.code == "OK") {
        that.getStepInfo(that.data.userInfo)
        that.getLDT()
        wx.showToast({
          title: '兑换成功!^_^',
        })
      }
    }).catch(e => {
      wx.showToast({
        title: '兑换失败！>_<',
      })
      console.log(e.errMsg)
    })
  }
}

//兑换商品
exchangeMerchandise = function (e) {
  console.log("兑换事件", e)
  var dat = e.currentTarget.dataset
  var that = this
  if (app.globalData.hasUserInfo) {
    var data = e.currentTarget.dataset
    var user = app.globalData.userInfo
    if (data.amount < 1) {
      wx.showToast({
        title: '您来晚了，商品都被领完啦！',
        icon: 'none'
      })
    } else {
      //是否登录叨币道获取的userId
      if (!that.data.isRegister) {
        that.setData({
          modalPattern: {
            title: "提示",
            content: "请先登录叨币道^_^",
            confirmText: "好的",
            cancelText: "下次吧",
          },
          modalConfirmEvent: "loginDaobidao",
          modalArgs: true,
        },
          that.showModal()
        )
      } else {
        if (dat.coin < dat.price) {
          wx.showToast({
            title: '叨币不够，快邀好友一起去兑换吧^_^',
            icon: 'none',
          })
          return
        }
        console.log("Cannot be here!")
        //是否兑换过没寄送的
        var param = {
          openId: user.openId,
          merchId: data.id
        }
        api.post(config.isExchangedUrl, param).then(res => {
          console.log("兑换检查\n", res)
          if (res.exchangeId != 0 && res.stat == 0) {
            wx.showToast({
              title: '已经兑换过啦！先领取礼包再来吧^_^',
              icon: 'none',
              image: '',
              duration: 1500,
              mask: true,
              success: function (res) { },
              fail: function (res) { },
              complete: function (res) { },
            })
            console.log("已经兑换过啦！")
          } else {
            that.setData({
              modalPattern: {
                title: "提示",
                content: "确定兑换吗",
                confirmText: "确定",
                cancelText: "再等等",
              },
              modalConfirmEvent: "exchangeConfirm",
              modalArgs: data
            },
              that.showModal()
            )
          }
        })
      }
    }
  } else {
    wx.showToast({
      title: "为保证程序功能可用，请先授权登录^_^",
      icon: 'none',
      duration: 1000,
    })
  }
}


nannerTitleColorLeftClick = function name(params) {
  var that = this;
  that.setData({
    nannerTitleColorLeft: '#4D7BFE',
    nannerTitleColorRight: '#000',
    bannerIndex: 0,
  })
}
nannerTitleColorRightClick = function name(params) {
  var that = this;
  that.setData({
    nannerTitleColorLeft: '#000',
    nannerTitleColorRight: '#4D7BFE',
    bannerIndex: 1,
  })
}
bannerChange = function (event) {
  var that = this;
  var index = event.detail.current;
  if (index === 0)
    that.setData({
      nannerTitleColorLeft: '#4D7BFE',
      nannerTitleColorRight: '#000',
    });
  else that.setData({
    nannerTitleColorLeft: '#000',
    nannerTitleColorRight: '#4D7BFE',
  });
}
/**
 * 测试邀请好友凑步数
 */
testInvitation = function (e) {
  if (!this.data.hasUserInfo) {
    wx.showToast({
      title: '错误!请先授权登录!',
      icon: 'none',
      image: '',
      duration: 2000,
      mask: true,
      success: function (res) {
        return
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  } else {
    var user = this.data.userInfo
    var step = this.data.stepInfo
    wx.navigateTo({
      url: './invitation/invitation?name=' + user.nickName + '&step=' + step.step + '&openId=' + user.openId,
    })
  }
}
}
// Page(new IndexPage()) //无预加载
Page(new IndexPage({clazzName: "IndexPage"}))
